#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import zipfile
import os
from datetime import datetime
import time

	
myRoot = "/home/Samba/Historie/"

for root, dirs, files in os.walk(myRoot): 
    for file in files:
        fullFileName = os.path.join(root, file)
        if zipfile.is_zipfile(fullFileName):
            zf = zipfile.ZipFile(fullFileName, "r")
            for name in zf.namelist():
#                inMemoryOutputFile = StringIO()
#                inMemoryOutputFile.write(zf.read(name))
                zfTimeStamp = zf.getinfo(name).date_time
                dtObject = datetime(*zfTimeStamp)
                dtStr = dtObject.strftime("%Y%m%d_%H%M%S")

                
                projectDirectory,dwgFileName = os.path.split(name.decode('ISO 8859-2'))
                fileNameNoExtension, ext = os.path.splitext(dwgFileName)
                zipFileName = u"%s_%s%s" % (fileNameNoExtension, dtStr, ".zip")
                targetDir = u"/home/Samba/Zmeny/%s/" % projectDirectory
                dwgFileName = u"%s" % dwgFileName
                print "targetDir:", targetDir
                print "dwgFileName:", dwgFileName
                print "zipFileName:", zipFileName
                try:            
                    os.makedirs(targetDir)
                       
                except OSError:
                    if os.path.isdir(targetDir):
                        # We are nearly safe
                        pass                

                newZip = zipfile.ZipFile(targetDir+zipFileName, "w")
#                dwgFileName = dwgFileName.decode('utf-8')
                dwgFileName = dwgFileName.encode('CP852') # Latin2
#                dwgFileName = dwgFileName.encode('ISO 8859-2') # Latin2
                print "name:", name
                newZip.writestr(dwgFileName,zf.read(name), zipfile.ZIP_DEFLATED)
                newZip.close()
                
